package cn.mw.cmdb.trigger;


import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Data
public class MwCmdbNotifyParam {

    @Schema(description = "id")
    private String id;

    @Schema(description = "标题")
    @NotBlank(message = "input-require-error")
    private String title;

    @Schema(description = "范围")
    private List<MwCmdbNotifyScopeParam> scopeParam;

    @Schema(description = "提醒规则")
    private MwNotifyRule notifyRule;

    @Schema(description = "执行类型")
    private MwNotifyExeType exeType;

    //前端回显用
    @Schema(description = "执行类型名称")
    private String exeTypeName;

    @Schema(description = "时间计划id")
    private String timePlanId;

    @Schema(description = "定时任务id")
    private List<Long> taskIds;

    @Schema(description = "触发器名称")
    private String triggerName;

    @Schema(description = "消息发送规则")
    private List<MwMessageRule> messageRules;

    @Schema(description = "用户组")
    private List<Long> groups;

    @Schema(description = "机构组")
    private List<List<Long>> orgs;

    public void extractFrom(MwCmdbNotify mwCmdbNotify, Map<String, String> idMap) {
        MwNofityScope mwNofityScope = mwCmdbNotify.getScope();
        if (null != mwNofityScope
                && (null != mwNofityScope.getModelGroupIds()
                || null != mwNofityScope.getModelIds()
                || null != mwNofityScope.getInstanceIds())
        ) {
            scopeParam = new ArrayList<>();
            if (null != mwNofityScope.getModelGroupIds()) {
                doExctractScope(scopeParam, mwNofityScope.getModelGroupIds(), idMap, MwNotifyScopeType.modelGroup);
            }

            if (null != mwNofityScope.getModelIds()) {
                doExctractScope(scopeParam, mwNofityScope.getModelIds(), idMap, MwNotifyScopeType.model);
            }

            if (null != mwNofityScope.getInstanceIds()) {
                doExctractScope(scopeParam, mwNofityScope.getInstanceIds(), idMap, MwNotifyScopeType.instance);
            }
        }
    }

    private void doExctractScope(List<MwCmdbNotifyScopeParam> scope ,List<String> items ,Map<String, String> idMap ,MwNotifyScopeType type){
        if(null != items){
            for(String item : items){
                String name = idMap.get(item);
                if(StringUtils.hasText(name)){
                    MwCmdbNotifyScopeParam param = new MwCmdbNotifyScopeParam(item ,name ,type);
                    scope.add(param);
                }
            }
        }
    }
}
